import uuid,time
from typing import List,Dict

class Slot:
    def __init__(self, role: str, content: str, metadata: dict=None):
        self.slot_id = uuid.uuid4().hex
        self.role = role
        self.content = content
        self.metadata = metadata or {}
        self.timestamp = int(time.time())

    def to_dict(self):
        return {
            "slot_id": self.slot_id,
            "role": self.role,
            "content": self.content,
            "timestamp": self.timestamp,
            "metadata": self.metadata
        }

    def to_prompt_line(self) ->str:
        return f'{self.role} :{self.content}'


class ContextChain:
    def __init__(self):
        self.slots: List[Slot] = []

    def add_slot(self, slot: Slot):
        self.slots.append(slot)

    def as_prompt(self) -> str:
        return '\n'.join([s.to_prompt_line() for s in self.slots])

def inject(context:List[str],slot:Slot) ->List[str]:
    context.append(slot.to_prompt_line())
    return context

def injectChain(context:List[str],slots:List[Slot]) -> List[str]:
    for slot in slots:
        context.append(slot.to_prompt_line())
    return context

def compress(slots:List[Slot]) -> Slot:
    text = ":".join(s.content for s in slots)
    return Slot(role="summary",content=f"压缩摘要：{text}")

class SemanticGroup:
    def __init__(self,topic:str):
        self.topic = topic
        self.slots: List[Slot] = []

    def add_slot(self, slot: Slot):
        self.slots.append(slot)

    def summarize(self) -> Slot:
        merged = ",".join([s.content for s in self.slots])
        return Slot(role="summary",content=f"{self.topic} 总结：{merged}")

def resolve(chain:List[Slot],requred_keywords:List[str]) -> List[Slot]:
    return [slot for slot in chain if any(k in slot.content for k in requred_keywords)]

class ExecutionContext:
    def __init__(self,task_id:str,context_chain:ContextChain):
        self.task_id = task_id
        self.context_chain = context_chain
        self.created_at = time.time()

    def get_prompt(self):
        return self.context_chain.as_prompt()



if __name__ == '__main__':
    #创建slot并构造ContextChain
    slot1 = Slot(role="user",content="你好，我向买一台笔记恩本")
    slot2 = Slot(role="assistant", content="请问预算是多少")
    slot3 = Slot(role="user", content="在2000元以内")

    chain = ContextChain()
    chain.add_slot(slot1)
    chain.add_slot(slot2)
    chain.add_slot(slot3)

    #inject和injectchain
    prompt_lines = []
    prompt_lines = inject(prompt_lines,slot1)
    prompt_lines = injectChain(prompt_lines,[slot2,slot3])

    #compress
    compress_slot = compress([slot1,slot3])

    #semantic group
    group = SemanticGroup("用户游戏需求")
    group.add_slot(slot1)
    group.add_slot(slot3)

    #execution context
    ctx = ExecutionContext("task-001",chain)

    print(ctx)